﻿using System;
using NHibernate;

namespace DataLayer.UoW
{
    public static class UnitOfWork
    {
        private static IUnitOfWorkFactory unitOfWorkFactory = new UnitOfWorkFactory();
        private static IUnitOfWork innerUnitOfWork;

        /// <summary>
        /// Starts a new unit of work.
        /// </summary>
        /// <returns></returns>
        public static IUnitOfWork Start()
        {
            if (innerUnitOfWork != null)
            {
                log4net.LogManager.GetLogger(typeof(UnitOfWork)).Error("You cannot start more than one unit of work at the same time.");
                throw new InvalidOperationException("You cannot start more than one unit of work at the same time.");
            }
            innerUnitOfWork = unitOfWorkFactory.Create();
            return innerUnitOfWork;
        }

        /// <summary>
        /// The current unit of work.
        /// </summary>
        public static IUnitOfWork Current
        {
            get
            {
                if (innerUnitOfWork == null)
                {
                    log4net.LogManager.GetLogger(typeof(UnitOfWork)).Error("You are not in a unit of work");
                    throw new InvalidOperationException("You are not in a unit of work");
                }
                return innerUnitOfWork;
            }
        }

        /// <summary>
        /// Specifies whether the unit of work has started.
        /// </summary>
        public static bool IsStarted
        {
            get
            {
                return innerUnitOfWork != null;
            }
        }

        public static ISession CurrentSession
        {
            get { return unitOfWorkFactory.CurrentSession; }
            internal set { unitOfWorkFactory.CurrentSession = value; }
        }

        internal static void DisposeUnitOfWork(UnitOfWorkImplementor adapter)
        {
            innerUnitOfWork = null;
        }
    }
}
